package com.jdbc.dao;

import com.jdbc.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;

public class UserDao {
    private JdbcTemplate jdbcTemplate;

    private DataSourceTransactionManager transactionManager;

    public User selectById(Integer id) {
        String sql = "select user_id as userId,username as userName,password,employee_id as employeeId,salt from sys_user where user_id = ?";
        User user = jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<User>(User.class));
        return user;
    }

    /**
     * 批量插入数据
     *
     * @param list
     */
    public void batchInsert(List<User> list) {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            for (User user : list) {
                insert(user);
            }
            transactionManager.commit(status);
        } catch (RuntimeException e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    /**
     * <h2></h2>
     *
     * @param user
     * @return
     */
    public Integer insert(User user) {
        String sql = "INSERT INTO sys_user (user_id,username,password,employee_id,salt) VALUES (?,?,?,?,?)";
        int update = jdbcTemplate.update(sql, new Object[]{
                user.getUserId(), user.getUserName(), user.getPassword(), user.getEmployeeId(), user.getSalt()
        });
        return update;
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    public DataSourceTransactionManager getTransactionManager() {
        return transactionManager;
    }

    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
}
